package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.commcon.DateUtil;
import com.example.eci_quartz.cloudcc.commcon.ReplaceNameUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *T+1获取DBS系统中的客户数据(操作插入或更新)
 */
public class AccountImpl2 extends baseDao{
	static String binding = InsertXMInfo();
	/**
	 *T+1获取DBS系统中的客户数据(操作插入或更新)
	 * 客户信息
	 * @throws SQLException
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	public static String upsertAccount(){
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Map> updatelist =null;
		List<Map> insertlist =null;
		//====================================客户开始更新====================
		ReplaceNameUtil nameUtil=null;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE)-650);
	    String firstDay=format.format(cal.getTime());
        //获取系统当天时间
        String newDate=format.format(new Date());
		String info = "false";
		String sql="select * FROM LIBJ49FSMS.CUSTNEW CO "
			     +" WHERE CO.LSMN8 <'"+firstDay+"' or CO.LSMN8 is null";
		Map<String,Map> rsMap=null;
		Map<String,Map> kfgmMap=null;
		Map<String, Map>  hydmMap=null;
		Map<String, Map>  ccuserMap=null;
		try {
			 String khdms="";//拼接客户编号
			 conn= new DefaultConnectionFactory().getConnection();
			 pstmt = conn.prepareStatement(sql);
			 rs = pstmt.executeQuery();
			 rsMap=new HashMap<String,Map>();//map<客户代码，客户数据>从DBS查询出来的
			 kfgmMap=getkfgmMap();//获取客户规模
			 ccuserMap=CommonMethod.getUserByName(binding);//获取用户
			 nameUtil=new ReplaceNameUtil();
			 int count=0;
			 hydmMap=gethydmMap();//行业代码
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//客户编号---20190316
					String khdm=(rs.getString("CUNO") == null ? "" : rs.getString("CUNO")+ "").trim();
					if(khdm!=null&&!"".equals(khdm)){
						khdms+="'"+khdm+"',";//拼接客户代码
					}
					mapObj.put("sfjktb", 1);
					mapObj.put("khdm", khdm);
					String khdz1=(rs.getString("CUADD1") == null ? "" : rs.getString("CUADD1")+ "").trim();
					String name=(rs.getString("CUNM")==null?"":rs.getString("CUNM")+ "").trim()+(rs.getString("CUNM2") == null ? "" : rs.getString("CUADD1")+"").trim()+khdz1;
					String newName = nameUtil.getNewName(khdm,name);
					//客户名称
					mapObj.put("name", newName);
					//mcpy 名称拼音
					mapObj.put("mcpy",(rs.getString("CUSRK") == null ? "" : rs.getString("CUSRK")+ "").trim());
					//分公司 +仓库
					String ck =(rs.getString("STN1") == null ? "" : rs.getString("STN1")+ "").trim();
					mapObj.put("ck",ck);//仓库
					// 财务账号
					mapObj.put("cwzh", (rs.getString("VATID") == null ? "" : rs.getString("VATID")+ "").trim());
					//客户规模
					String kfgm=(rs.getString("CUTYP") == null ? "" : rs.getString("CUTYP")+ "").trim();
					mapObj.put("kfgm", (kfgmMap.get(kfgm)==null?"":kfgmMap.get(kfgm)+"").trim());
					String khdz2=(rs.getString("CUADD2") == null ? "" : rs.getString("CUADD2")+ "").trim();
					String khdz3=(rs.getString("CUADD3") == null ? "" : rs.getString("CUADD3")+ "").trim();
					//通讯地址
					mapObj.put("khdz2", khdz2+khdz3);
					//客户是否停用  Y:否;N:是
					String khsfty=(rs.getString("FLGDLI") == null ? "" : rs.getString("FLGDLI")+ "").trim();
					if(khsfty!=null&&!"".equals(khsfty)&&!khsfty.equals("null")){
						if(khsfty.equals("Y")){
							mapObj.put("khsfty","否");
						}else if(khsfty.equals("N")){
							mapObj.put("khsfty","是");
						}
					}else {
						mapObj.put("khsfty","");
					}

					//	CSR覆盖人员 零件
					String csrfgry=(rs.getString("SLMNM") == null ? "" : rs.getString("SLMNM")+"").trim();
					mapObj.put("csrfgry",csrfgry);
					//系统用户
					mapObj.put("csrccuser",(ccuserMap.get(csrfgry)==null?"":ccuserMap.get(csrfgry)+"").trim());
					//	CSR覆盖人员 零件	名称简写
					mapObj.put("csrmcjx",(rs.getString("SLMN02") == null ? "" : rs.getString("SLMN02")+"").trim());
					//CIC-1
					String CIC1= (rs.getString("IDCD01") == null ? "" : rs.getString("IDCD01")+ "").trim();
					mapObj.put("CIC1",hydmMap.get(CIC1));
					//支付方式  1：；2：
					String zffs=(rs.getString("TERMCD") == null ? "" : rs.getString("TERMCD")+ "").trim();
					if(zffs!=null&& !"".equals(zffs)&&!zffs.equals("null")){
						if(zffs.equals("1")){
							mapObj.put("zffs","现金");
						}else if(zffs.equals("2")){
							mapObj.put("zffs","赊销");
						}
					}else {
						mapObj.put("zffs","");
					}
					//dbs创建日期
					mapObj.put("dbscjsj",DateUtil.getDatetoStringUtil((rs.getString("DTSYS8") == null ? "" : rs.getString("DTSYS8")+ "").trim()));
					//修改日期
					mapObj.put("dbsxgsj",DateUtil.getDatetoStringUtil((rs.getString("LSMN8") == null ? "" : rs.getString("LSMN8")+ "").trim()));
					//dbscjsj
					if(khdm!=null&&!"".equals(khdm)) {
						rsMap.put(khdm, mapObj);//放在集合中
					}
				}
			}
			//查询CRM系统中的客户信息，根据从DBS系统中的客户代码查询的客户数据
			//拼接客户代码
			if(khdms!=null&&!"".equals(khdms)){
				updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
			    Map<String, Map> khMap =null;
			    khMap=getAccount(khdms.substring(0,khdms.length()-1));//从Cloudcc平台取数，判断该客户是否存在
			    //判断客户是新增还是更新
				if(rsMap.size()>0&&rsMap!=null){
					for(String khdm:rsMap.keySet()){
						Map khObj=rsMap.get(khdm);//获取DBS中的客户数据
						//CRM系统中有客户信息
						if(khMap!=null){
							if(khMap.containsKey(khdm)) {// 更新客户信息// 更新客户信息
								Map khMaps =khMap.get(khdm);
								khObj.put("id", khMaps.get("id"));
								khObj.put("sjlx", "DBS");
								updatelist.add(khObj);
							}else{
								khObj.put("sjlx","DBS");
								insertlist.add(khObj);
							}
						}
					}
				}
			}

			//插入新客户
			if (insertlist!=null&&insertlist.size() > 0) {
				Map<Integer,List> map =DataGroupUtil.dataOneGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						if("".equals(binding)){
							binding=CommonMethod.getBingAgain();
						}
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=Account&data="+jsonstr+"&binding=";
			            String insertinfo=operate(data_insert+ binding);//用http方式调用insert方法，插入客户信息

			            //判断binding是否失效，如果失效，就重新获取
			            JSONObject fromObject =null;
			            String result="";
						if(CommonMethod.isJSONValid(insertinfo)){
							fromObject = JSONObject.fromObject(insertinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							insertinfo=operate(data_insert+binding);
						}
					    info="insert_success";
					}
				}
			}
			//更新老客户
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						if("".equals(binding)){
							binding=CommonMethod.getBingAgain();
						}
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=Account&data="+jsonstr_update+"&binding="; //Lt 不走触发器
     		            String updateInfo=operate(data_update+ binding);//用http方式调用update方法，更新客户信息

     		           //判断binding是否失效，如果失效，就重新获取
     		            JSONObject fromObject =null;
			            String result="";
						if(CommonMethod.isJSONValid(updateInfo)){
							fromObject = JSONObject.fromObject(updateInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							updateInfo=operate(data_update+binding);
						}

					    info="update_success";
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs!= null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}
	/**
	  *查询客户规模 kfgm
	  * */
	@SuppressWarnings("rawtypes")
	public static Map getkfgmMap(){
		String data_query = "serviceName=cqlQuery&objectApiName=kfgm" +
				"&expressions=select id,gmdm from kfgm " +
				"where gmdm is not null and is_deleted='0'&binding=";
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		Map<String, String> ckMap =null;
		try {
			if("".equals(binding)){
				binding=CommonMethod.getBingAgain();
			}
			ckMap = new HashMap<String, String>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+binding);//通过http方式调用咱们平台的查询方法
	        //判断binding是否失效，如果失效，就重新获取
            JSONObject fromObject =null;
            String result="";
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				for (int i = 0; i <5; i++) {
					khinfo=operate(data_query+binding);
					if(CommonMethod.isJSONValid(khinfo)){
						fromObject = JSONObject.fromObject(khinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if("true".equals(result)){
						break;
					}
				}
			}
			String returninfo = "[" + khinfo + "]";// 手动转换成json格式，方便取值
			if (!"[]".equals(returninfo)&&khinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (!"[]".equals(kh_datas)&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						String gmdm=(accObj.get("gmdm")==null?"":accObj.get("gmdm").toString()).trim();
						if(gmdm!=null&&!"".equals(gmdm)){
							ckMap.put(accObj.get("gmdm").toString(), accObj.get("id").toString());
						}

					}
				}
			}
		}catch (Exception e) {
		}
		return ckMap;
	}
	/**
	  *查询行业代码 hydm
	  * */
	@SuppressWarnings("rawtypes")
	public static Map gethydmMap(){
		String data_query = "serviceName=cqlQuery&objectApiName=hydm" +
				"&expressions=select id,code from hydm " +
				"where code is not null and is_deleted='0' &binding=";
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		Map<String, String> ckMap =null;
		try {
			if("".equals(binding)){
				binding=CommonMethod.getBingAgain();
			}
			ckMap = new HashMap<String, String>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+binding);//通过http方式调用咱们平台的查询方法
	        //判断binding是否失效，如果失效，就重新获取
		    JSONObject fromObject =null;
            String result="";
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				for (int i = 0; i <5; i++) {
					khinfo=operate(data_query+binding);
					if(CommonMethod.isJSONValid(khinfo)){
						fromObject = JSONObject.fromObject(khinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if("true".equals(result)){
						break;
					}
				}
			}
			String returninfo = "[" + khinfo + "]";// 手动转换成json格式，方便取值
			if (!"[]".equals(returninfo)&&khinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (!"[]".equals(kh_datas)&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						String code=(accObj.get("code")==null?"":accObj.get("code").toString()).trim();
						if(code!=null&&!"".equals(code)){
							ckMap.put(accObj.get("code").toString(), accObj.get("id").toString());
						}
					}
				}
			}
		}catch (Exception e) {
		}
		return ckMap;
	}
	/**
	  * 查询客户代码不为空的客户信息
	  * */
	@SuppressWarnings("rawtypes")
	public static Map getAccount(String ids){
		String data_query = "serviceName=cqlQuery&objectApiName=Account&expressions="
				+ "select id,name,khdm from Account where khdm is not null and is_deleted='0' "
				+ "and khdm in ("+ids+")&binding=";//查询客户信息
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		String result="";
		Map<String, Map> khMap = null;
		try {
			if("".equals(binding)){
				binding=CommonMethod.getBingAgain();
			}
			khMap=new HashMap<String, Map>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+ binding);//通过http方式调用咱们平台的查询方法
	        //判断binding是否失效，如果失效，就重新获取
	        JSONObject fromObject =null;
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				for (int i = 0; i <5; i++) {
					khinfo=operate(data_query+binding);
					if(CommonMethod.isJSONValid(khinfo)){
						fromObject = JSONObject.fromObject(khinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if("true".equals(result)){
						break;
					}
				}
			}
			String returninfo = "["+khinfo+"]";// 手动转换成json格式，方便取值
			if (returninfo != "[]") {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (!"[]".equals(kh_datas)&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						JSONObject acc_newObj = new JSONObject();    //新的json，只存id，编号
						String khdm = accObj.get("khdm") == null? "" : accObj.get("khdm")+ "";
						if (!"".equals(khdm)) {
							if (!khMap.containsKey(khdm)) {
								acc_newObj.put("id", accObj.get("id"));
								acc_newObj.put("khdm", accObj.get("khdm"));
								khMap.put(khdm, acc_newObj);
							}
						}
					}
				}
			}
		}catch (Exception e) {
		}
		return khMap;
	}

}
